package com.innovation.chengzhangriji.ui;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.JsonElement;
import com.innovation.chengzhangriji.Baby;
import com.innovation.chengzhangriji.Config;
import com.innovation.chengzhangriji.R;
import com.innovation.chengzhangriji.database.DatabaseManager;
import com.innovation.chengzhangriji.http.Auth;
import com.innovation.chengzhangriji.http.BabyAllResponse;
import com.innovation.chengzhangriji.http.Client;
import com.innovation.chengzhangriji.http.ResponseHandler;
import com.innovation.chengzhangriji.preferences.LoginInfo;
import com.innovation.chengzhangriji.ui.widget.CuteButton;
import com.innovation.chengzhangriji.ui.widget.CuteTextView;
import com.innovation.chengzhangriji.ui.widget.CuteToolbar;
import com.innovation.chengzhangriji.ui.widget.CuteTwoImageButton;
import com.makeramen.roundedimageview.RoundedImageView;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.orhanobut.logger.Logger;

public class AdminActivity extends BaseActivity implements CuteToolbar.OnClickCuteToolbarListener, View.OnClickListener {

    private static final int REQUEST_CODE = 1000;

    private CuteTwoImageButton btnSuper;

    private CuteTwoImageButton btnNormal;

    private CuteTwoImageButton btnWrite;

    private CuteTwoImageButton btnRead;

    private CuteTwoImageButton btnReady;

    private CuteTwoImageButton btnStart;

    private CuteTwoImageButton btnGrow;

    private CuteTwoImageButton btnAdd;

    private RelativeLayout layoutWriteRead;

    private LinearLayout layoutWrite;

    private int userId;

    private int role;

    private int permission;

    private int range;

    private Auth auth;

    private DisplayImageOptions options;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Logger.d("删除联系人");
        if (requestCode == REQUEST_CODE && resultCode == RESULT_OK) {
            // 网络请求
            LoginInfo loginInfo = Config.getLoginInfo(this);
            if (loginInfo == null) {
                return;
            }
            String phone = loginInfo.getPhone();
            String token = loginInfo.getToken().getAccessToken();
            int babyId = loginInfo.getBabyID();
            Client.requestCancel(this, phone, token, babyId, userId, new ResponseHandler() {

                @Override
                public void onInnovationStart() {
                    showProgressDialog(null, null);
                }

                @Override
                public void onInnovationSuccess(JsonElement value) {
                    setResult(RESULT_OK);
                    finish();
                }

                @Override
                public void onInnovationFinish() {
                    dismissProgressDialog();
                }

                @Override
                public void onInnovationExceptionFinish() {
                    dismissProgressDialog();
                }

            }, networkUnavailableSampleImpl());
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_admin);
        CuteToolbar toolbar = (CuteToolbar) findViewById(R.id.toolbar);
        RoundedImageView imageHead = (RoundedImageView) findViewById(R.id.image_head);
        CuteTextView textName = (CuteTextView) findViewById(R.id.text_name);
        CuteTextView textPhone = (CuteTextView) findViewById(R.id.text_phone);
        CuteTextView textDate = (CuteTextView) findViewById(R.id.text_date);
        CuteButton btnCancel = (CuteButton) findViewById(R.id.btn_cancel);
        layoutWriteRead = (RelativeLayout) findViewById(R.id.layout_write_read);
        layoutWrite = (LinearLayout) findViewById(R.id.layout_write);
        btnSuper = (CuteTwoImageButton) findViewById(R.id.btn_super);
        btnNormal = (CuteTwoImageButton) findViewById(R.id.btn_normal);
        btnWrite = (CuteTwoImageButton) findViewById(R.id.btn_write);
        btnRead = (CuteTwoImageButton) findViewById(R.id.btn_read);
        btnReady = (CuteTwoImageButton) findViewById(R.id.btn_ready);
        btnStart = (CuteTwoImageButton) findViewById(R.id.btn_start);
        btnGrow = (CuteTwoImageButton) findViewById(R.id.btn_grow);
        btnAdd = (CuteTwoImageButton) findViewById(R.id.btn_add);

        ImageView imageReady = (ImageView) findViewById(R.id.image_ready);
        ImageView imageStart = (ImageView) findViewById(R.id.image_start);
        ImageView imageGrow = (ImageView) findViewById(R.id.image_grow);
        ImageView imageAdd = (ImageView) findViewById(R.id.image_add);

        TextView textReady = (TextView) findViewById(R.id.text_ready);
        TextView textStart = (TextView) findViewById(R.id.text_start);
        TextView textGrow = (TextView) findViewById(R.id.text_grow);
        TextView textAdd = (TextView) findViewById(R.id.text_add);

        toolbar.setOnClickCuteToolbarListener(this);
        btnCancel.setOnClickListener(this);
        btnSuper.setOnClickListener(this);
        btnNormal.setOnClickListener(this);
        btnWrite.setOnClickListener(this);
        btnRead.setOnClickListener(this);
        btnReady.setOnClickListener(this);
        btnStart.setOnClickListener(this);
        btnGrow.setOnClickListener(this);
        btnAdd.setOnClickListener(this);

        String sPermission = getIntent().getStringExtra("permission");
        BabyAllResponse babyAllResponse = get(sPermission, BabyAllResponse.class);
        if (babyAllResponse == null) {
            return;
        }
        toolbar.setCuteTitle(babyAllResponse.getName());
        textName.setText(babyAllResponse.getName());
        textPhone.setText(babyAllResponse.getPhone());
        String type = null;
        switch (babyAllResponse.getType()) {
            case 1:
                type = "创建日记";
                break;
            case 2:
                type = "由" + babyAllResponse.getUser() + "邀请加入";
                break;
            case 3:
                type = "由" + babyAllResponse.getUser() + "批准加入";
                break;
        }
        userId = babyAllResponse.getUserId();
        auth = babyAllResponse.getAuth();
        role = babyAllResponse.getAuth().getRole();
        switch (role) {
            case 0:
                btnNormal.setTwoState();
                layoutWriteRead.setVisibility(View.VISIBLE);
                layoutWrite.setVisibility(View.INVISIBLE);
                break;
            case 1:
                btnSuper.setTwoState();
                layoutWriteRead.setVisibility(View.INVISIBLE);
                layoutWrite.setVisibility(View.VISIBLE);
                break;
        }
        permission = babyAllResponse.getAuth().getPermission();
        switch (permission) {
            case 0:
                btnRead.setTwoState();
                break;
            case 1:
                btnWrite.setTwoState();
                break;
        }
        // 判断宝宝现在的阶段
        LoginInfo loginInfo = Config.getLoginInfo(this);
        if (loginInfo == null) {
            return;
        }
        String userId = loginInfo.getUserID();
        int babyId = loginInfo.getBabyID();
        Baby baby = DatabaseManager.getInstance(this).queryBaby(userId, babyId);
        btnReady.setVisibility(View.GONE);
        btnStart.setVisibility(View.GONE);
        btnGrow.setVisibility(View.GONE);

        imageReady.setVisibility(View.GONE);
        imageStart.setVisibility(View.GONE);
        imageGrow.setVisibility(View.GONE);

        textReady.setVisibility(View.GONE);
        textStart.setVisibility(View.GONE);
        textGrow.setVisibility(View.GONE);

        if (Client.EMPTY_TIME != baby.getLastDate()) {
            btnReady.setVisibility(View.VISIBLE);
            imageReady.setVisibility(View.VISIBLE);
            textReady.setVisibility(View.VISIBLE);
            btnStart.setTwoDrawable(getResources().getDrawable(R.drawable.btn_select_mid_1), getResources().getDrawable(R.drawable.btn_select_mid_2));
            btnGrow.setTwoDrawable(getResources().getDrawable(R.drawable.btn_select_mid_1), getResources().getDrawable(R.drawable.btn_select_mid_2));
        }
        if (Client.EMPTY_TIME != baby.getDueDate()) {
            btnStart.setVisibility(View.VISIBLE);
            imageStart.setVisibility(View.VISIBLE);
            textStart.setVisibility(View.VISIBLE);
            btnGrow.setTwoDrawable(getResources().getDrawable(R.drawable.btn_select_mid_1), getResources().getDrawable(R.drawable.btn_select_mid_2));
        }
        if (Client.EMPTY_TIME != baby.getBirthday()) {
            btnGrow.setVisibility(View.VISIBLE);
            imageGrow.setVisibility(View.VISIBLE);
            textGrow.setVisibility(View.VISIBLE);
        }

        btnReady.setOneState();
        btnStart.setOneState();
        btnGrow.setOneState();
        btnAdd.setOneState();

        range = babyAllResponse.getAuth().getRange();
        Logger.d("时期" + range);
        switch (range) {
            case 0: // 加入
                btnAdd.setTwoState();
                break;
            case 1: // 备孕期
                btnReady.setTwoState();
                break;
            case 2: // 孕期
                btnStart.setTwoState();
                break;
            case 3: // 成长期
                btnGrow.setTwoState();
                break;
        }

        textDate.setText(babyAllResponse.getServerTS() + '\0' + type);
        setOptions();
        ImageLoader.getInstance().displayImage(babyAllResponse.getPath(), imageHead, options);

    }

    @Override
    public void onClickLeft() {
        if (auth.getRole() == role && auth.getPermission() == permission && auth.getRange() == range) {
            finish();
        } else {
            // 网络请求
            LoginInfo loginInfo = Config.getLoginInfo(this);
            if (loginInfo == null) {
                return;
            }
            String phone = loginInfo.getPhone();
            String token = loginInfo.getToken().getAccessToken();
            int babyId = loginInfo.getBabyID();
            Client.requestSetPermission(this, phone, token, babyId, userId, role, permission, range, new ResponseHandler() {

                @Override
                public void onInnovationStart() {
                    showProgressDialog(null, null);
                }

                @Override
                public void onInnovationSuccess(JsonElement value) {
                    super.onInnovationSuccess(value);
                    setResult(RESULT_OK);
                    finish();
                }

                @Override
                public void onInnovationFinish() {
                    dismissProgressDialog();
                }

                @Override
                public void onInnovationExceptionFinish() {
                    dismissProgressDialog();
                }

            }, networkUnavailableSampleImpl());
        }
    }

    @Override
    public void onClickRight() {

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_cancel:
                Intent intent = new Intent(this, CancelTipDialogActivity.class);
                startActivityForResult(intent, REQUEST_CODE);
                break;
            case R.id.btn_super:
                if (btnSuper.isSelect()) {
                    return;
                }
                role = 1;
                btnSuper.setTwoState();
                btnNormal.setOneState();
                layoutWrite.setVisibility(View.VISIBLE);
                layoutWriteRead.setVisibility(View.INVISIBLE);
                permission = 1;
                tip(4);
                break;
            case R.id.btn_normal:
                if (btnNormal.isSelect()) {
                    return;
                }
                role = 0;
                btnSuper.setOneState();
                btnNormal.setTwoState();
                layoutWrite.setVisibility(View.INVISIBLE);
                layoutWriteRead.setVisibility(View.VISIBLE);
                permission = 1;
                btnWrite.setTwoState();
                btnRead.setOneState();
                tip(5);
                break;
            case R.id.btn_write:
                if (btnWrite.isSelect()) {
                    return;
                }
                permission = 1;
                btnWrite.setTwoState();
                btnRead.setOneState();
                break;
            case R.id.btn_read:
                if (btnRead.isSelect()) {
                    return;
                }
                permission = 0;
                btnWrite.setOneState();
                btnRead.setTwoState();
                break;
            case R.id.btn_ready:
                if (btnReady.isSelect()) {
                    return;
                }
                range = 1;
                btnReady.setTwoState();
                btnStart.setOneState();
                btnGrow.setOneState();
                btnAdd.setOneState();
                break;
            case R.id.btn_start:
                if (btnStart.isSelect()) {
                    return;
                }
                range = 2;
                btnReady.setOneState();
                btnStart.setTwoState();
                btnGrow.setOneState();
                btnAdd.setOneState();
                break;
            case R.id.btn_grow:
                if (btnGrow.isSelect()) {
                    return;
                }
                range = 3;
                btnReady.setOneState();
                btnStart.setOneState();
                btnGrow.setTwoState();
                btnAdd.setOneState();
                break;
            case R.id.btn_add:
                if (btnAdd.isSelect()) {
                    return;
                }
                range = 0;
                btnReady.setOneState();
                btnStart.setOneState();
                btnGrow.setOneState();
                btnAdd.setTwoState();
                break;
        }
    }

    private void tip(int i) {
        Intent intent = new Intent(this, TipDialogActivity.class);
        intent.putExtra("state", i);
        startActivity(intent);
    }

    private void setOptions() {
        options = new DisplayImageOptions.Builder()
                .showImageOnLoading(R.drawable.ic_head_circle_default_small)    //在ImageView加载过程中显示图片
                .showImageForEmptyUri(R.drawable.ic_head_circle_default_small)  //image连接地址为空时
                .showImageOnFail(R.drawable.ic_head_circle_default_small)  //image加载失败
                .cacheOnDisk(true)   //加载图片时会在磁盘中加载缓存
                .build();
    }
}
